package com.dreamlin.gankio.mvvm.home.other

import androidx.lifecycle.MutableLiveData
import androidx.recyclerview.widget.DiffUtil
import com.dreamlin.gankio.base.model.BaseViewModel
import com.dreamlin.gankio.base.ui.DiffBaseAdapter
import com.dreamlin.gankio.mvvm.home.GankEntity
import com.dreamlin.gankio.mvvm.home.feature.pageSize
import com.dreamlin.gankio.net.NetHelper
import com.dreamlin.gankio.net.RxHelper
import com.dreamlin.gankio.net.WrapperBean
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import java.net.URLEncoder


/**
 * <p> Title: OtherViewModel </p>
 * <p> Description: </p>
 * @author:  dreamlin
 * @date:    9/20/20
 * @version: V1.0.0
 * Created by dreamlin on 9/20/20.
 */
class OtherViewModel : BaseViewModel() {

    var diffCllBack: GankEntityDiffCallback? = null
    var diffResult: DiffUtil.DiffResult? = null
    val gankEntities = MutableLiveData<WrapperBean<List<GankEntity>>>()

    fun loadMoreData(type: String, page: Int, count: Int) {
        val typeEncode = URLEncoder.encode(type, "UTF-8")
        val subscribe = NetHelper.api.listCategoryData(typeEncode, page, count)
            .compose(RxHelper.applySchedulersWithoutLoading(this))
            .compose(RxHelper.handleGlobalError(this))
            .subscribe({
                gankEntities.value = it
            }, { it.printStackTrace() })
        addDisposable(subscribe)
    }

    fun refreshData(adapter: DiffBaseAdapter<GankEntity>, oldEntities: List<GankEntity>, type: String) {
        val typeEncode = URLEncoder.encode(type, "UTF-8")
        val subscribe = NetHelper.api.listCategoryData(typeEncode, 1, pageSize)
            .subscribeOn(Schedulers.io())
            .map {
                //calculate diff
                if (it.data.isNotEmpty()) {
                    if (diffCllBack == null) {
                        diffCllBack = GankEntityDiffCallback(oldEntities, it.data)
                    } else {
                        diffCllBack?.setOldAndNewData(oldEntities, it.data)
                    }
                    diffResult = DiffUtil.calculateDiff(diffCllBack!!, false)
                }
                return@map it
            }
            .observeOn(AndroidSchedulers.mainThread())
            .compose(RxHelper.handleGlobalError(this))
            .subscribe({
                diffResult?.dispatchUpdatesTo(adapter)
                gankEntities.value = it
            }, { it.printStackTrace() })
        addDisposable(subscribe)
    }

}